import json

from django.db.models import Q
from django.shortcuts import render

# Create your views here.
from django.views import View
from django.http import JsonResponse, HttpResponseForbidden
from chats.models import ChatData, GroupUser,GroupData
from users.models import User, Friend
from .utails import get_chat_count


class FindsView(View):
    '''发现'''
    def get(self):
        pass

class ToGroupView(View):
    def get(self, request):
        userid = request.GET.get('userid', None)
        if userid is None:
            return HttpResponseForbidden('400')
        try:
            user = User.objects.get(id=userid)
        except:
            return HttpResponseForbidden('400')
        usergroup = GroupUser.objects.filter()
        return JsonResponse()

class GroupsList(View):
    #  通讯录 群列表
    def get(self,request):
        userid = request.GET.get('userid', None)
        if userid is None:
            return HttpResponseForbidden('400')
        try:
            user = User.objects.get(id=userid)
        except:
            return HttpResponseForbidden('400')
        # 获取群聊信息
        groups = user.user_g.all()  # 这里是usergroup
        content = []
        for j in groups:
            content.append({
                'id': j.group.id,
                'userimg': j.group.group_img,
                'username': j.group.groupname,
                'new_data': j.group.new_data,
                'datetime': j.update_time,
                'group': 1,
                'tip': j.tip
            })
        return JsonResponse(content, safe=False)


class FriendsView(View):
    '''通讯录'''
    def get(self, request):
        userid = request.GET.get('userid', None)
        if userid is None:
            return HttpResponseForbidden('400')
        try:
            user = User.objects.get(id=userid)
        except:
            return HttpResponseForbidden('400')
        # 获取好友信息
        friends = Friend.objects.filter(Q(user_a=user) | Q(user_b=user), status=1).order_by('-update_time')
        content = []
        for i in friends:
            userM = i.user_b if i.user_a == user else i.user_a
            content.append({
                'id': f'{userM.id}',
                "username": f'{userM.username}',
                'userimg': f'{userM.default_image}',
                'new_data': f'{i.mew_data}',
                'tip': f'{get_chat_count(user, userM)}',
                'datetime': f'{i.update_time}'
            })
        return JsonResponse(content, safe=False)


class IndexView(View):
    # 获取首页信息
    def get(self, request):
        userid = request.GET.get('userid', None)
        if userid is None:
            return HttpResponseForbidden('400')
        try:
            user = User.objects.get(id=userid)
        except:
            return HttpResponseForbidden('400')

        # 获取好友信息
        friends = Friend.objects.filter(Q(user_a=user) | Q(user_b=user), status=1).order_by('-update_time')
        # 获取群聊信息
        groups = user.user_g.all()  # 这里是usergroup

        content = {'users': [], 'groups': []}
        for i in friends:
            userM = i.user_b if i.user_a == user else i.user_a
            content['users'].append({
                'id': f'{userM.id}',
                "username": f'{userM.username}',
                'userimg': f'{userM.default_image}',
                'new_data': f'{i.mew_data}',
                'tip': f'{get_chat_count(user, userM)}',
                'datetime': f'{i.update_time}'
            })
        for j in groups:
            content['groups'].append({
                'id': j.group.id,
                'userimg': j.group.group_img,
                'username': j.group.groupname,
                'new_data': j.group.new_data,
                'datetime': j.update_time,
                'group': 1,
                'tip': j.tip
            })
        return JsonResponse(content, safe=False)


class SearchView(View):
    # 搜索
    def get(self, request):
        search = request.GET.get('search', None)
        userid = request.GET.get('userid', None)
        if search is None or userid is None:
            return HttpResponseForbidden('400')

        try:
            main = User.objects.get(id=userid)
        except:
            return HttpResponseForbidden('400')

        if search == '':
            return JsonResponse([], safe=False)

        # 搜索用户
        users = User.objects.filter(Q(email__icontains=search) | Q(username__icontains=search))
        # 搜索群聊
        group = GroupData.objects.filter(groupname__icontains=search)

        content = {'users': [], 'groups': []}

        for i in users:
            content['users'].append({
                'id': i.id,
                'username': i.username,
                'email': i.email,
                'userimg': i.default_image,
            })
        for g in group:
            content['groups'].append({
                'id':g.id,
                'groupname':g.groupname,
                'group_img':g.group_img
            })
        # 只能带一个数组
        return JsonResponse(content, safe=False)


class FrendsData(View):
    def get(self, request):
        userid = request.GET.get('userid', None)
        if userid is None:
            return HttpResponseForbidden('400')
        try:
            user = User.objects.get(id=userid)
        except:
            return HttpResponseForbidden('400')

        friends = Friend.objects.filter(Q(user_a=user) | Q(user_b=user), status=1)
        if len(friends) == 0:
            return JsonResponse([], safe=False)
        content = []
        for i in friends:
            content.append({
                'id_a': i.user_a.id,
                'id_b': i.user_b.id
            })

        return JsonResponse(content, safe=False)
